package com.github.hgkmail.hello.aspect;

import com.github.hgkmail.hello.annotation.PrintMethod;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Aspect //切面
public class PrintMethodAspect {

    public static final Logger logger = LoggerFactory.getLogger(PrintMethodAspect.class);

    @Pointcut("@annotation(com.github.hgkmail.hello.annotation.PrintMethod)") //切点表达式
    public void PrintMethodAspect() {

    }

    @Around("PrintMethodAspect()")  //advice 切面逻辑
    public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {  //JoinPoint 连接点（切点的具体实例）
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        Method method = methodSignature.getMethod();
        PrintMethod printMethod = method.getAnnotation(PrintMethod.class);
        logger.info("Before method {}", method.getName());

        if (printMethod.showArgs() && method.getParameterCount()>0) {
            List<String> params = new ArrayList<>();
            for (Object param:pjp.getArgs()) {
                params.add(param.toString());
            }
            logger.info("args: {}", params);
        }

        Object ret = pjp.proceed();

        logger.info("After method {}", method.getName());

        return ret;
    }

}
